package com.aura.springbook.controller;

import com.aura.springbook.common.R;
import com.aura.springbook.common.constant.BookConstants;
import com.aura.springbook.common.util.PageUtil;
import com.aura.springbook.common.util.ResponseUtil;
import com.aura.springbook.model.BorrowRecord;
import com.aura.springbook.model.request.BorrowRequest;
import com.aura.springbook.model.vo.BorrowRecordVO;
import com.aura.springbook.service.BookService;
import com.aura.springbook.service.BorrowRecordService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/borrows")
@Tag(name = "借阅记录接口", description = "图书借阅相关操作接口")
public class BorrowRecordController {
    
    private static final Logger logger = LoggerFactory.getLogger(BorrowRecordController.class);
    
    @Autowired
    private BorrowRecordService borrowRecordService;
    
    @Autowired
    private BookService bookService;
    
    /**
     * 借阅图书（创建记录）
     */
    @PostMapping
    @Operation(summary = "借阅图书", description = "创建图书借阅记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "借阅成功"),
        @ApiResponse(responseCode = "400", description = "图书库存不足"),
        @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<Map<String, Object>> borrowBook(@RequestBody BorrowRequest borrowRequest) {
        logger.info("收到借阅图书请求, 用户ID: {}, 图书ID: {}", borrowRequest.getUserId(), borrowRequest.getBookId());
        
        try {
            Long recordId = borrowRecordService.borrowBook(borrowRequest.getUserId(), borrowRequest.getBookId());
            Map<String, Object> data = new HashMap<>();
            data.put("id", recordId);
            logger.info("借阅图书成功, 借阅记录ID: {}, 用户ID: {}, 图书ID: {}", recordId, borrowRequest.getUserId(), borrowRequest.getBookId());
            return ResponseUtil.success(data);
        } catch (Exception e) {
            logger.error("借阅图书失败, 用户ID: {}, 图书ID: {}, 错误信息: {}", borrowRequest.getUserId(), borrowRequest.getBookId(), e.getMessage(), e);
            return ResponseUtil.fail(com.aura.springbook.common.exception.ResultCode.BOOK_STOCK_EMPTY, e.getMessage());
        }
    }
    
    /**
     * 归还图书（更新记录）
     */
    @PutMapping("/{id}/return")
    @Operation(summary = "归还图书", description = "更新图书借阅记录为已归还状态")
    @Parameter(name = "id", description = "借阅记录ID", required = true)
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "归还成功"),
        @ApiResponse(responseCode = "400", description = "归还失败"),
        @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<String> returnBook(@PathVariable Long id) {
        logger.info("收到归还图书请求, 借阅记录ID: {}", id);
        
        try {
            boolean result = borrowRecordService.returnBook(id);
            if (result) {
                logger.info("归还图书成功, 借阅记录ID: {}", id);
                return ResponseUtil.success(BookConstants.MSG_BOOK_RETURN_SUCCESS);
            } else {
                logger.warn("归还图书失败, 借阅记录ID: {}", id);
                return ResponseUtil.fail(com.aura.springbook.common.exception.ResultCode.RETURN_FAIL);
            }
        } catch (Exception e) {
            logger.error("归还图书失败, 借阅记录ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ResponseUtil.fail(com.aura.springbook.common.exception.ResultCode.RETURN_FAIL, e.getMessage());
        }
    }
    
    /**
     * 查询我的借阅记录（分页）
     */
    @GetMapping("/user/{uid}")
    @Operation(summary = "查询用户借阅记录", description = "根据用户ID分页查询借阅记录")
    @Parameters({
        @Parameter(name = "uid", description = "用户ID", required = true),
        @Parameter(name = "page", description = "页码，默认为1"),
        @Parameter(name = "size", description = "每页大小，默认为10")
    })
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "400", description = "分页参数不合法")
    })
    public R<IPage<BorrowRecordVO>> getBorrowRecordsByUser(
            @PathVariable Long uid,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        logger.debug("收到查询用户借阅记录请求, 用户ID: {}, 页码: {}, 每页大小: {}", uid, page, size);
        
        // 验证分页参数
        if (!PageUtil.validatePageParams(page, size)) {
            logger.warn("查询用户借阅记录失败, 分页参数不合法, 用户ID: {}, 页码: {}, 每页大小: {}", uid, page, size);
            return ResponseUtil.paramError("分页参数不合法");
        }
        
        page = PageUtil.getDefaultPage(page);
        size = PageUtil.getDefaultSize(size);
        
        IPage<BorrowRecord> records = borrowRecordService.getBorrowRecordsByUser(uid, page, size);
        
        // 转换为VO对象，包含图书标题
        IPage<BorrowRecordVO> voPage = PageUtil.convert(records, record -> {
            BorrowRecordVO vo = new BorrowRecordVO();
            // 只设置需要的字段
            vo.setId(record.getId());
            vo.setBorrowTime(record.getBorrowTime());
            vo.setReturnTime(record.getReturnTime());
            vo.setStatus(record.getStatus());
            
            // 设置图书标题
            com.aura.springbook.model.Book book = bookService.getById(record.getBookId());
            if (book != null) {
                vo.setBookTitle(book.getTitle());
            }
            
            return vo;
        });
        
        logger.debug("查询用户借阅记录成功, 用户ID: {}, 总记录数: {}", uid, voPage.getTotal());
        return ResponseUtil.success(voPage);
    }
    
    /**
     * 查询单个借阅记录
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询借阅记录详情", description = "根据借阅记录ID查询详细信息")
    @Parameter(name = "id", description = "借阅记录ID", required = true)
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "记录不存在")
    })
    public R<BorrowRecord> getBorrowRecordDetail(@PathVariable Long id) {
        logger.debug("收到查询借阅记录详情请求, 借阅记录ID: {}", id);
        
        BorrowRecord record = borrowRecordService.getBorrowRecordDetail(id);
        if (record != null) {
            logger.debug("查询借阅记录详情成功, 借阅记录ID: {}", id);
            return ResponseUtil.success(record);
        } else {
            logger.warn("查询借阅记录详情失败, 借阅记录ID: {} 不存在", id);
            return ResponseUtil.notFound();
        }
    }
}